import paramiko
import os


def upload(ip, username, password, filename, dest):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect(ip, 22, username, password, timeout=10)
        sftp = ssh.open_sftp()
        sftp.put(filename, dest)
        print 'upload %s finish' % dest
    except Exception, e:
        print 'upload failed: ', e
    finally:
        ssh.close()


def upload_dir_exec(ip, username, password, dir_path, cmd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    filenames = os.listdir(dir_path)
    try:
        ssh.connect(ip, 22, username, password, timeout=10)
        sftp = ssh.open_sftp()
        for filename in filenames:
            file_path = os.path.join(dir_path, filename)
            sftp.put(file_path, filename)
            print 'upload %s finish' % filename
        stdin, stdout, stderr = ssh.exec_command(cmd)
        print 'exec finish, waiting response...'
        out = stdout.readlines()
        for o in out:
            print o.replace('\n', '')
    except Exception, e:
        print 'upload dir and exec failed: ', e
    finally:
        ssh.close()


def ssh_exec(ip, username, password, cmd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect(ip, 22, username, password, timeout=10)
        stdin, stdout, stderr = ssh.exec_command(cmd)
        print 'exec finish, waiting response...'
        out = stdout.readlines()
        for o in out:
            print o.replace('\n', '')
        return out
    except Exception, e:
        print 'ssh failed: ', e
        return None
    finally:
        ssh.close()
